package com.killer;

import com.killer.config.RpcConfig;
import com.killer.handler.RpcServerHandler;
import com.killer.rpc.RpcDecoder;
import com.killer.rpc.RpcRequest;
import com.killer.serializer.JsonSerializer;
import com.killer.service.UserService;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author ：Killer
 * @date ：Created in 20-11-27 上午9:23
 * @description：${description}
 * @modified By：
 * @version: version
 */
public class RpcServer {

    public static void main(String[] args) throws InterruptedException {
        RpcServer server=new RpcServer();
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(RpcConfig.class);
        server.start();
    }

    public void start() throws InterruptedException {
        //创建两个线程组 bossGroup负责监听请求 workerGroup负责进行读写操作
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        //创建启动引导类
        ServerBootstrap serverBootstrap=new ServerBootstrap();
        //配置启动引导类
        serverBootstrap.group(bossGroup, workerGroup)//绑定线程池
                //指定使用的channel
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                //绑定客户端连接时触发的操作
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        String ip=socketChannel.localAddress().getHostName();
                        int port=socketChannel.localAddress().getPort();
                        System.out.println("接收到ip:"+ip+"，端口号:"+port+"的连接");
                        //获取pipeline
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        //添加Rpc解码器用于解码客户端发起的rpc请求
                        pipeline.addLast(new RpcDecoder(new JsonSerializer(), RpcRequest.class));
                        //添加String编码器用于返回解码
                        pipeline.addLast(new StringEncoder());
                        //添加Rpc服务处理类
                        pipeline.addLast(new RpcServerHandler());

                    }
                });
        //服务器异步创建绑定端口
        ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();
        //等待服务监听端口关闭
        channelFuture.channel().closeFuture().sync();
    }
}
